function getUrlRequest(){
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            if (str.indexOf("&") != -1) {
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            } else {
                var key = str.substring(0,str.indexOf("="));
                var value = str.substr(str.indexOf("=")+1);
                theRequest[key] = decodeURI(value);
            }
        }
        return theRequest;
    }
	
	var Request = new Object();
    Request = getUrlRequest();
	var tempID;
	var tstId;
	
	var action;
	action = Request["action"];
	tempID = Request["id"];
	//$.messager.alert("操作提示","tempID0:"+tempID);
	// $.messager.alert("操作提示",action);

        function getUserName(){
        	return realname;
        }
        function getUserNo(){
        	return userno;
        }
	
	var Keditor;
	KindEditor.ready(function(K) {
		Keditor = K.create('textarea[name="remark"]', {
			resizeType : 1,
			allowPreviewEmoticons : false,
			allowImageUpload : true,
			// uploadJson:'../../assets/scripts/kindeditor/jsp/upload_json.jsp', //上传图片的java代码，只不过放在jsp中
			afterUpload: function(){this.sync();}, //图片上传后，将上传内容同步到textarea中
            afterBlur: function(){this.sync();},   ////失去焦点时，将上传内容同步到textarea中
			items : [
				'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
				'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
				'insertunorderedlist', '|', 'table','emoticons', 'image', 'link']
		});
	});

	function getTextAreaHtml(){
		Keditor.sync();
		return Keditor.html();
	}

	function setKediterDisable(){
		Keditor.readonly(true);
	}

	$(function(){		
		console.log("action");
		if (action==1) {//新增
			document.getElementById('item_id').value=tempID;
			console.log("item_id:"+document.getElementById('item_id').value);
			//test(tempID);
			// $("#item_id").textbox('setValue',tempID]);
			// loadDatagrid(tempID);
			if(Request["tstId"]!=0){				
				console.log("tstId:"+Request["tstId"]);
				tstId = Request["tstId"];
				$("#itemForm").form("load",{
	       			template_id:tstId,
	       			isrt_emp_id:userno,
	       			isrt_emp_name:realname,
	       			update_emp_id:userno,
	       			update_emp_name:realname,
	       		});
	       		// Keditor.html('');
			}else{
				$("#itemForm").form("load",{
	       			isrt_emp_id:userno,
	       			isrt_emp_name:realname,
	       			update_emp_id:userno,
	       			update_emp_name:realname,
	       			
	       		});
	       		// Keditor.html('');
       		}
		};
		if(action==2){//修改
			
			$.ajax({
		       url : '../../api/NJ_searchTestItemByID?id='+tempID,
		       method:'get',

		       success : function(item) {
		       		console.log("acton1");
		       		console.log("action:"+action);
		       		console.log("tempID:"+tempID);
		       		

		       		$("#itemForm").form("load",{
		       			item_id:item["item_id"],
		       			item_name:item["item_name"],
		       			template_id:item["template_id"],
		       			template_name:item["template_name"],
		       			tool:item["tool"],
		       			cost:item["cost"],
		       			additionalCharge:item["additionalCharge"],
		       			chargeUnit:item["chargeUnit"],
		       			judgingBasis:item["judgingBasis"],
		       			// remark:item["remark"],
		       			remarks:item["remarks"],
		       			isrt_emp_id:item["isrt_emp_id"],
		       			isrt_emp_name:item["isrt_emp_name"],
		       			isrt_date:item["isrt_date"],
		       			update_emp_id:userno,
		       			update_emp_name:realname,
		       			update_date:item["update_date"]
		       		});
		       		Keditor.html('');
		       		Keditor.html(item["remark"]);
		       		test(tempID,action);
		       		setstdItemName($('#item_name').textbox('getValue'));
	        	}
        	});
    		
    		
    		
		};
		if(action==3){//查看
			// $.messager.alert("操作提示","查看");
			// $.messager.alert("操作提示","tempID:"+tempID);
			$.ajax({
		       url : '../../api/NJ_searchTestItemByID?id='+tempID,
		       method:'get',
		       success : function(item) {
		       		$("#itemForm").form("load",{
		       			item_id:item["item_id"],
		       			item_name:item["item_name"],
		       			template_id:item["template_id"],
		       			template_name:item["template_name"],
		       			tool:item["tool"],
		       			cost:item["cost"],
		       			additionalCharge:item["additionalCharge"],
		       			chargeUnit:item["chargeUnit"],
		       			judgingBasis:item["judgingBasis"],
		       			remark:item["remark"],
		       			remarks:item["remarks"],
		       			isrt_emp_id:item["isrt_emp_id"],
		       			isrt_emp_name:item["isrt_emp_name"],
		       			isrt_date:item["isrt_date"],
		       			update_emp_id:item["update_emp_id"],
		       			update_emp_name:item["update_emp_name"],
		       			update_date:item["update_date"]
		       		});
		       		Keditor.html('');
		       		Keditor.html(item["remark"]);
		       		// Keditor.remove();
		       		Keditor.readonly(true);
		       		test(tempID,action);
		       		setstdItemName($('#item_name').textbox('getValue'));
	        	}
        	});

        	$("#itemMessagetb").find("input,button,textarea,select").attr("disabled", "disabled");
        	$('#saveButton').attr("disabled", "disabled");
        	$('#remark').attr("disabled", "disabled");
		};

		
	});

	

	
	
	$(document).ready(function() {
		$("#saveButton").click(function saveInfo() {
			
			var param = $("#itemForm").serializeArray();
			//param=$('#item_id').textbox('getValue');
			param[11].value=getTextAreaHtml();
			
			var saveUrl="";
			console.log($('#item_name').textbox('getValue'));
			if($('#item_name').textbox('getValue')==null ||$('#item_name').textbox('getValue')=='undefined'||$('#item_name').textbox('getValue')==''){
				$.messager.alert("操作提示","请填写完整信息！");
			}else{
			
			if (action==1) {
				saveUrl="../../api/NJ_insertTestItem";
			};
			if (action==2) {
				saveUrl="../../api/NJ_editTestItem";
			};
			// var d = $('#validdeadline').datetimebox('getValue');
			console.log(param);
			$.ajax({
				url: saveUrl,
				type: 'get',
				dataType: 'json',
				data: param,
				success:function(r){
					console.log("r:"+r);
					
					if (r>0) {
						$("#itemMessagetb").find("input,button,textarea,select").attr("disabled", "disabled");
						setKediterDisable();
						setstdItemName($('#item_name').textbox('getValue'));
						test($('#item_id').textbox('getValue'),3);
						$('#dg').datagrid('reload');
						$.messager.show({
							msg : r.msg,
							title : '成功'
						});
						if(action==1){
							setstdItemID(r);
							setstdItemName($('#item_name').textbox('getValue'));
						}

						//操作日志
						if(action==1){
							saveSystemLog("标准项维护","www.ktsy.com/menu_nj/TestStandardManage/TestStandardSubitem","3","添加标准项",realname,userno);
						}
						if(action==2){
							saveSystemLog("标准项维护","www.ktsy.com/menu_nj/TestStandardManage/TestStandardSubitem","6","修改标准项",realname,userno);
						}
					}
					if(r==-1){
						$.messager.alert("操作提示",'保存失败，请检查项目名称是否重复！');
					}
					if(r==0){
						$.messager.alert("操作提示",'保存失败！');
					}
				},
				error:function() {
					// $.messager.alert("操作提示","错误"+param);
				},
				complete:function(){
					$('#edit').dialog('close');
					datagrid.datagrid('reload');
				}			
			});
			}			
		});
    	
	});
	
	//记录用户登录系统日志
	function saveSystemLog(pagetitle,page,operation,detail,userrealname,userno){
		// $.messager.alert("操作提示","保存日志信息");
		$.ajax({
	        type:"get",
	        dataType : "json",
	        url:"../../api/insertSystemLog",
	        data:{pagetitle:pagetitle,page:page,operation:operation,detail:detail,userrealname:userrealname,userno:userno},
	        success:function(r){
	            if (r==1){
	            	console.log("保存"+r+"条日志信息");
	          	}
	        }
      	});
	}


				// var stdID=document.getElementById("item_id").value;

				// console.log($('#item_id').textbox('getValue'));
				var datagrid;
				var rowEditor=undefined;
				var editRow=undefined;
				var stdItemID;
				var stdItemName;			

				$(function(){
					// console.log("stdID:"+stdID);
					datagrid=$("#dg").datagrid({
						// url:"../../api/getAllTestStandardSubiterm?standardItermID="+stdID,//加载的URL
						url:"",
						method:"get",
					    idField:"id",
					    rownumbers: true, //是否加行号
					    singleSelect:true,
						//pagination:true,//显示分页
						//pageSize:5,//分页大小
						//pageList:[5,10,20,30,40],//每页的个数
						//beforePageText: '第',//页数文本框前显示的汉字 
				       // afterPageText: '页    共 {pages} 页', 
				        //displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录', 
						//fit:true,//自动补全
						width:1200,
			            height:250,
						fitColumns:true,
						title:"工况管理",
						columns:[[      //每个列具体内容
						  	{ field:'ck',checkbox:true}, 
							{field:'id',title:'标准子项ID',width:100,hidden:true
							}, 
							{field:'name',title:'工况',width:100,
								editor : {
									type : 'validatebox',
									options : {
						               	required : true
									}
								}
							}, 
							{field:'standardItermID',title:'标准项ID',width:100,hidden:true
							}, 
							{field:'item_name',title:'标准项',width:100,},
							{field:'testInDry',title:'室内干温',width:100,
								editor : {
									type : 'validatebox',
									options : {
										required : true
									}
								}
							},					
							{field:'inDryUnit',title:'室内干温单位',width:100,
								editor : {
									type : 'combobox',
					             	options : {
						                valueField: "value", 
						                textField: "label",
						                panelHeight:'auto',
						                data:[
				                			{
												label: '摄氏度℃',
												value: '℃',
											},
											{
												label: '华氏度℉',
												value: '℉',
											},
											{
												label: '开尔文K',
												value: 'K',
											}
										],
						                required : true
									}
								}
							}, 
							{field:'testInDamp',title:'室内湿温',width:100,
								editor : {
									type : 'validatebox',
									options : {
										required : true
									}
								}
							}, 
							{field:'inDampUnit',title:'室内湿温单位',width:100,
								editor : {
									type : 'combobox',
					             	options : {
						                valueField: "value", 
						                textField: "label",
						                panelHeight:'auto',
						                data:[
				                			{
												label: '摄氏度℃',
												value: '℃',
											},
											{
												label: '华氏度℉',
												value: '℉',
											},
											{
												label: '开尔文K',
												value: 'K',
											}
										],
						                required : true
									}
								}
							}, 
							{field:'testOutDry',title:'室外干温',width:100,
								editor : {
									type : 'validatebox',
									options : {
										required : true
									}
								}
							}, 						 
							{field:'outDryUnit',title:'室外干温单位',width:100,
								editor : {
									type : 'combobox',
					             	options : {
						                valueField: "value", 
						                textField: "label",
						                panelHeight:'auto',
						                data:[
				                			{
												label: '摄氏度℃',
												value: '℃',
											},
											{
												label: '华氏度℉',
												value: '℉',
											},
											{
												label: '开尔文K',
												value: 'K',
											}
										],
						                required : true
									}
								}
							},
							{field:'testOutDamp',title:'室外湿温',width:100,
								editor : {
									type : 'validatebox',
									options : {
										required : true
									}
								}
							},
							{field:'outDampUnit',title:'室外湿温单位',width:100,
								editor : {
									type : 'combobox',
					             	options : {
						                valueField: "value", 
						                textField: "label",
						                panelHeight:'auto',
						                data:[
				                			{
												label: '摄氏度℃',
												value: '℃',
											},
											{
												label: '华氏度℉',
												value: '℉',
											},
											{
												label: '开尔文K',
												value: 'K',
											}
										],
						                required : true
									}
								}
							},
							{field:'needTime',title:'需要时间(小时)',width:100,
								editor : {
									type : 'validatebox',
									options : {
										required : true
									}
								}
							},
							{field:'testTime',title:'实验用时(小时)',width:100,
								editor : {
									type : 'validatebox',
									options : {
										required : true
									}
								}
							},
							{field:'addUser',title:'添加人',width:100,},
							{field:'addTime',title:'添加时间',width:100,},
							{field:'mark',title:'标志',width:100,hidden:true
			     			},
		    			]],
						toolbar:[              //工具条
			        		{text:"增加",iconCls:"icon-ktsyAdd",handler:function(){
			        			
			        			$.messager.alert("操作提示",'请先保存标准项信息')
			        		}},
					        {text:"删除",iconCls:"icon-ktsyDelete",handler:function(){
			        			
			        			$.messager.alert("操作提示",'请先保存标准项信息')
			        		}},
					        {text:"修改",iconCls:"icon-ktsyEdit",handler:function(){
			        			
			        			$.messager.alert("操作提示",'请先保存标准项信息')
			        		}},					       
					        {text:"保存",iconCls:"icon-ktsySave",handler:function(){
			        			
			        			$.messager.alert("操作提示",'请先保存标准项信息')
			        		}},
					        {text:"取消编辑",iconCls:"icon-ktsyCancel",handler:function(){
			        			
			        			$.messager.alert("操作提示",'请先保存标准项信息')
			        		}},
					       			       
			        	],
						onAfterEdit:function(rowIndex, rowData, changes){
							var inserted = datagrid.datagrid('getChanges', 'inserted');
							var updated = datagrid.datagrid('getChanges', 'updated');
							if (inserted.length < 1 && updated.length < 1) {
								editRow = undefined;
								datagrid.datagrid('unselectAll');
								return;
							}

							var url = '';
							         
							if (inserted.length > 0) {
								url = '../../api/NJ_insertTestStandardSubiterm';
							}
							
							if (updated.length > 0) {
								url = '../../api/NJ_editTestStandardSubiterm';
							}
							$.ajax({
								url : url,
								data : rowData,
								dataType : 'json',
								success : function(r) {
									if (r==1) {
										datagrid.datagrid('acceptChanges');
										$.messager.show({
											msg : r.msg,
											title : '成功'
										});
										editRow = undefined;
										datagrid.datagrid('reload');


										//操作记录
										if(url == '../../api/NJ_insertTestStandardSubiterm'){
    										saveSystemLog("标准子项维护","www.ktsy.com/menu_nj/TestStandardManage/TestStandardSubitem","3","增加标准子项",realname,userno);
										}
										if(url == '../../api/NJ_editTestStandardSubiterm'){
											saveSystemLog("标准子项维护","www.ktsy.com/menu_nj/TestStandardManage/TestStandardSubitem","6","修改标准子项",realname,userno);
										}
									}else if(r==7){
										$.messager.alert("操作提示",'子项目名称不能重复！');
										datagrid.datagrid('beginEdit', editRow);
										
									} else {
										/*datagrid.datagrid('rejectChanges');*/
										datagrid.datagrid('beginEdit', editRow);
										$.messager.alert('错误', r.msg, 'error');
									}
									datagrid.datagrid('unselectAll');
								}
							});
						},
						onDblClickCell:function(rowIndex, field, value){
							if(rowEditor==undefined)
							{
					        	datagrid.datagrid('beginEdit',rowIndex);
					        	rowEditor=rowIndex;
							}
							
						}
				});
			});

    		



   			function test(itemID,action){ //设置datagrid数据加载路径
   				stdItemID=itemID;//设置itemID
				$("#dg").datagrid({
					url:"../../api/NJ_getAllTestStandardSubiterm?standardItermID="+itemID					
				});
				if(action==3){//判断是否加载工具条
					initToolBar();
				}
			};
			function setstdItemID(itemID){ //设置itemID
				stdItemID=itemID;
				console.log(stdItemID);
				initToolBar();
			};
			function setstdItemName(tName){
				stdItemName=tName;
			};

			function initToolBar(){
				$("#dg").datagrid({
					
					toolbar:[              //工具条
			        		{text:"增加",iconCls:"icon-ktsyAdd",handler:function(){//回调函数
			        			console.log(stdItemID);
					        	if(rowEditor==undefined)
								{
					        		datagrid.datagrid('insertRow',{//如果处于未被点击状态，在第一行开启编辑
						        		index: 0,	
						        		row: {
						        			standardItermID:stdItemID,
						        			addUser:getUserName(),
						        			item_name:stdItemName
						        		}						        		
						        	});
					        		rowEditor=0;
						        	datagrid.datagrid('beginEdit',rowEditor);//没有这行，即使开启了也不编辑  
								}
			        

			        		}},
					        {text:"删除",iconCls:"icon-ktsyDelete",handler:function(){
					        	var rows=datagrid.datagrid('getSelections');
					  			console.log("rows[0]:");
					  			console.log(rows[0]);
					        	if(rows.length<=0)
					        	{
					        		$.messager.alert('警告','您没有选择','error');
					        	}
					        	else if(rows.length>1)
					        	{
					        		$.messager.alert('警告','不支持批量删除','error');
					        	}
					        	else
					        	{
					        		$.messager.confirm('确定','您确定要删除吗',function(t){
					        			if(t)
					        			{
					        				$.ajax({
					        					url : '../../api/NJ_deleteTestStandardSubiterm',
					        					data : rows[0],
					        					dataType : 'json',
					        					success : function(r) {
					        						if (r==1) {
					        							datagrid.datagrid('acceptChanges');
					        							$.messager.show({
					        								msg : r.msg,
					        								title : '成功'
					        							});
					        							editRow = undefined;
					        							datagrid.datagrid('reload');

					        							//操作记录
		        										saveSystemLog("标准子项维护","www.ktsy.com/menu_nj/TestStandardManage/TestStandardSubitem","4","删除标准子项",realname,userno);
					        						} else {
					        							/*datagrid.datagrid('rejectChanges');*/
					        							datagrid.datagrid('beginEdit', editRow);
					        							$.messager.alert('错误', r.msg, 'error');
					        						}
					        						datagrid.datagrid('unselectAll');
					        					}
					        				});
					        			}
					        		})
					        	}
					        }},
					        {text:"修改",iconCls:"icon-ktsyEdit",handler:function(){
					        	var rows=datagrid.datagrid('getSelections');
					        	if(rows.length==1)
					        	{
					        		if(rowEditor==undefined)
									{
					        			var index=datagrid.datagrid('getRowIndex',rows[0]);
					        			 rowEditor=index;
					        			datagrid.datagrid('unselectAll');
							        	datagrid.datagrid('beginEdit',index);
							        	
									}
					        	}
					        }},
					        
					        {text:"保存",iconCls:"icon-ktsySave",handler:function(){
					        	
					        	datagrid.datagrid('endEdit',rowEditor);
					        	rowEditor=undefined;
					        }},
					        {text:"取消编辑",iconCls:"icon-ktsyCancel",handler:function(){
					        	rowEditor=undefined;
					        	datagrid.datagrid('rejectChanges')
					        }},					        		       
			        	]
				});
			}
